import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getRoles, hasPermission } from '@/utils/auth'

const whiteList = ['/login']

router.beforeEach((to, from, next) => {
    NProgress.start()
    if (to.meta && to.meta.header_title) {
        document.title = to.meta.header_title
    }
    if (getRoles()) {
        if (to.path === '/login') {
            next({ path: '/' })
            NProgress.done()
        } else {
            if (!store.getters.getMenus || store.getters.getMenus.length === 0) {
                store.dispatch('getPermission', store.getters.roles).then(res => {
                    store.dispatch('GenerateRoutes').then(() => {
                        next({ ...to, replace: true })
                    })
                })
            } else {
                if (to.path === "/") {
                    let paths = store.getters.getPaths;
                    let keys = Object.keys(paths);
                    let path = keys.length > 0 ? paths[keys[0]] : "/401"
                    next({ path, replace: true })
                } else {
                    if (hasPermission(store.getters.getMenus, to)) {
                        store.dispatch('SetDashboard', to.meta.dashboard)
                        store.dispatch('SetActivePanel', to.meta.panel)
                        next()
                    } else {
                        next({ path: '/401', replace: true })
                        NProgress.done()
                    }
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next('/login')
            NProgress.done()
        }
    }
})

router.afterEach(route => {
    NProgress.done()
})